package com.baizhi.bzmall.admin.handler;

import com.baizhi.bzmall.common.vo.ResultEntity;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class GlobalExceptionHandler implements HandlerExceptionResolver {
    @SneakyThrows
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        ObjectMapper objectMapper = new ObjectMapper();
        ex.printStackTrace();
        ResultEntity<Object> error = null;
        response.setCharacterEncoding("utf-8");
        if(ex instanceof AccessDeniedException){
            error = ResultEntity.builder(403, "权限不足").data();
        }else{
            error = ResultEntity.error(ex.getMessage());
        }
        String errorJson = objectMapper.writeValueAsString(error);

        PrintWriter pw = response.getWriter();
        pw.print(errorJson);
        pw.flush();

        return new ModelAndView(); //表示不再跳转
    }
}